package org.jeecg.modules.third.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.content.service.IConContentTemplateService;
import org.jeecg.modules.publish.entity.ThirdContentLink;
import org.jeecg.modules.publish.service.IThirdContentLinkService;
import org.jeecg.modules.third.entity.ThirdAccount;
import org.jeecg.modules.third.entity.ThirdInfo;
import org.jeecg.modules.third.service.IThirdAccountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.third.service.IThirdInfoService;
import org.jeecg.modules.third.vo.ThirdContentVo;
import org.jeecg.modules.third.vo.ThirdInfoVo;
import org.jeecg.util.DouYinUtil;
import org.jeecg.util.WechatUtil;
import org.jeecg.util.WeiBoUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: sys_third_account
 * @Author: jeecg-boot
 * @Date:   2021-12-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags="sys_third_account")
@RestController
@RequestMapping("/third/thirdAccount")
public class ThirdAccountController extends JeecgController<ThirdAccount, IThirdAccountService> {
	@Autowired
	private IThirdAccountService thirdAccountService;
	@Autowired
	private WeiBoUtil weiBoUtil;
	@Autowired
	private IThirdInfoService thirdInfoService;
	@Autowired
	private IThirdContentLinkService thirdContentLinkService;
	@Autowired
	private IConContentTemplateService conContentTemplateService;





	 @AutoLog(value = "sys_third_account-分页列表查询")
	 @ApiOperation(value="sys_third_account-分页列表查询", notes="sys_third_account-分页列表查询")
	 @GetMapping(value = "/getAllInfo")
	 public Result<?> getAllInfo() {
		 QueryWrapper<ThirdInfo> thirdInfoQueryWrapper = new QueryWrapper<>();
		 thirdInfoQueryWrapper.eq("del_flag",0);
		 List<ThirdInfo> thirdInfoList = thirdInfoService.list(thirdInfoQueryWrapper);
		 List<ThirdInfoVo> thirdInfoVoList = new ArrayList<>();
		 if(!CollectionUtil.isEmpty(thirdInfoList)){
			 thirdInfoList.forEach(e->{
				 ThirdInfoVo thirdInfoVo = new ThirdInfoVo();
				 thirdInfoVo.setPlatform( e.getPlatformName());
				 thirdInfoVo.setBaseId(e.getId());
				 QueryWrapper<ThirdAccount> queryWrapper = new QueryWrapper<>();
				 queryWrapper.eq("base_id",e.getId());
				 LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				 queryWrapper.eq("sys_user_id",loginUser.getId());
				 List<ThirdAccount> list = thirdAccountService.list(queryWrapper);
				 thirdInfoVo.setThirdAccountList(list);
				 thirdInfoVoList.add(thirdInfoVo);
			 });
		 }


//		 for (ThirdAccount thirdAccount : list) {
//			 QueryWrapper<ThirdContentLink> linkCount  = new QueryWrapper<>();
//			 linkCount.eq("account_id",thirdAccount.getId());
//
//			 linkCount.select("count(account_id) as articleCount");
//			 linkCount.select("sum(love_num) as readNum");
//			 linkCount.select("sum(read_num) as LoveNum");
//			 linkCount.select("sum(report_num) as reportNum");
//			 ThirdContentLink one = thirdContentLinkService.getOne(linkCount);
//			 thirdAccount.setArticleCount(one.getArtcileCount());
//			 thirdAccount.setSumRead(one.getReadNum());
//			 thirdAccount.setSumLove(one.getLoveNum());
//			 thirdAccount.setSumReport(one.getReportNum());
//
//
//		 }
		 return Result.OK(thirdInfoVoList);
	 }




	 /**
	  *
	  * @param baseId
	  * @return
	  */
	@AutoLog(value = "sys_third_account-分页列表查询")
	@ApiOperation(value="sys_third_account-分页列表查询", notes="sys_third_account-分页列表查询")
	@GetMapping(value = "/listByThirdType")
	public Result<?> queryPageList(String baseId) {
		QueryWrapper<ThirdAccount> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("base_id",baseId);
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		queryWrapper.eq("sys_user_id",loginUser.getId());
		List<ThirdAccount> list = thirdAccountService.list(queryWrapper);

		for (ThirdAccount thirdAccount : list) {
			QueryWrapper<ThirdContentLink> linkCount  = new QueryWrapper<>();
			linkCount.eq("account_id",thirdAccount.getId());

			linkCount.select("count(account_id) as articleCount");
			linkCount.select("sum(love_num) as readNum");
			linkCount.select("sum(read_num) as LoveNum");
			linkCount.select("sum(report_num) as reportNum");
			ThirdContentLink one = thirdContentLinkService.getOne(linkCount);
			thirdAccount.setArticleCount(one.getArtcileCount());
			thirdAccount.setSumRead(one.getReadNum());
			thirdAccount.setSumLove(one.getLoveNum());
			thirdAccount.setSumReport(one.getReportNum());


		}
		return Result.OK(list);
	}



	 @AutoLog(value = "sys_third_account-分页列表查询")
	 @ApiOperation(value="sys_third_account-分页列表查询", notes="sys_third_account-分页列表查询")
	 @GetMapping(value = "/articleListByType")
	 public Result<?> articleListByType(Integer type ,String accountId,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
										@RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {

		// LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 Page<ThirdContentVo> page = new Page<>(pageNo,pageSize);
		 Page<ThirdContentVo> perList = conContentTemplateService.getPerList(page, type, accountId);

		 return Result.OK(perList);
	 }


	 /**
	  * 分页列表查询
	  *
	  * @param thirdInfo
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "bas_third_info-分页列表查询")
	 @ApiOperation(value="bas_third_info-分页列表查询", notes="bas_third_info-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<?> queryPageList(ThirdInfo thirdInfo,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<ThirdInfo> queryWrapper = QueryGenerator.initQueryWrapper(thirdInfo, req.getParameterMap());
		 Page<ThirdInfo> page = new Page<ThirdInfo>(pageNo, pageSize);
		 IPage<ThirdInfo> pageList = thirdInfoService.page(page, queryWrapper);
		 return Result.OK(pageList);
	 }

	/**
	 * 添加
	 *
	 * @param thirdAccount
	 * @return
	 */
	@AutoLog(value = "sys_third_account-添加")
	@ApiOperation(value="sys_third_account-添加", notes="sys_third_account-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ThirdAccount thirdAccount) throws IOException {
		//微博
		ThirdInfo thirdInfo = thirdInfoService.getById(thirdAccount.getBaseId());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		thirdAccount.setSysUserId(sysUser.getId());

		if(thirdAccount.getThirdType().equals("4")){

				//微博
			JSONObject userInfo = weiBoUtil.getUserInfo(thirdInfo.getId(), thirdInfo.getClientKey(), thirdInfo.getClientSecret(), thirdAccount.getAuthorizationCode());
			String profileImageUrl = userInfo.getString("profile_image_url");
			String id = userInfo.getString("id");

			String screenName = userInfo.getString("screen_name");
			thirdAccount.setAvatar(profileImageUrl);
			thirdAccount.setThirdUserUuid(id);
			thirdAccount.setRealname(screenName);

		}else if(thirdAccount.getThirdType().equals("2")){
			//抖音
			Map<String, String> douYinInfo = DouYinUtil.getDouYinInfo(thirdInfo.getId(), thirdInfo.getClientKey(), thirdAccount.getAuthorizationCode());
			String token  = douYinInfo.get("access_token");
			String openId  = douYinInfo.get("open_id");

			thirdAccount.setThirdUserUuid(douYinInfo.get(openId));
			JSONObject douYinUserInfo = DouYinUtil.getDouYinInfo(openId, token);


			thirdAccount.setRealname(douYinUserInfo.getString("nickname"));
			thirdAccount.setAvatar(douYinUserInfo.getString("avatar"));

		}else if(thirdAccount.getThirdType().equals("1")){
			//微信
		}
		thirdAccountService.save(thirdAccount);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param thirdAccount
	 * @return
	 */
	@AutoLog(value = "sys_third_account-编辑")
	@ApiOperation(value="sys_third_account-编辑", notes="sys_third_account-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ThirdAccount thirdAccount) {
		thirdAccountService.updateById(thirdAccount);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "sys_third_account-通过id删除")
	@ApiOperation(value="sys_third_account-通过id删除", notes="sys_third_account-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		thirdAccountService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "sys_third_account-批量删除")
	@ApiOperation(value="sys_third_account-批量删除", notes="sys_third_account-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.thirdAccountService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "sys_third_account-通过id查询")
	@ApiOperation(value="sys_third_account-通过id查询", notes="sys_third_account-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ThirdAccount thirdAccount = thirdAccountService.getById(id);
		return Result.OK(thirdAccount);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param thirdAccount
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, ThirdAccount thirdAccount) {
      return super.exportXls(request, thirdAccount, ThirdAccount.class, "sys_third_account");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, ThirdAccount.class);
  }

}
